package com.suitbim.commandserver.commandserver.reveiver;

import com.suitbim.commandserver.commandserver.client.RevitCommandClient;
import com.suitbim.commandserver.commandserver.manage.FileManage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.util.concurrent.Semaphore;

@Deprecated
public class RevitCommandReceiver implements MessageListener {
    @Autowired
    private FileManage fileManage;

    @Autowired
    private RevitCommandClient client;

    private Semaphore clientSemaphore = new Semaphore(1, false);

    Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public void onMessage(Message message, byte[] bytes) {
        String channel = new String(message.getChannel());
        String body = new String(message.getBody());
        try {
            //这中监听无法保证单个运行
            clientSemaphore.acquire();
            log.info(client.getClientPath() + ":begin command execute");
            boolean success = client.execute(body);
            log.info(client.getClientPath() + ":command execute success:" + success);
            if (success) {
                fileManage.deleteFile(client.currentFile(body));
                log.info(client.getClientPath() + ":file deleted");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            log.info(client.getClientPath() + ":handle command finish");
            clientSemaphore.release();
        }
    }
}
